#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <algorithm>
#include <cctype>
#include <string>

using namespace std;

// 单词预处理：转小写并去除标点
string preprocess(const string &word) {
    string result;
    for (auto c : word) {
        if (isalpha(c)) {
            result += tolower(c);
        }
    }
    return result;
}

// 比较函数：按词频降序排序
bool compare(const pair<string, int> &a, const pair<string, int> &b) {
    return a.second > b.second;
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0]<< " <filename>" << endl;
        return 1;
    }

    ifstream file(argv[1]);
    if (!file) {
        cerr << "Failed to open file: " << argv[1] << endl;
        return 1;
    }

    map<string, int> wordCount;
    string word;
    while (file >> word) {
        string processed = preprocess(word);
        if (!processed.empty()) {
            wordCount[processed]++;
        }
    }

    // 输出所有单词词频（按词典序）
    cout << "所有单词词频：" << endl;
    for (auto &entry : wordCount) {
        cout << entry.first << ": " << entry.second << endl;
    }

    // 输出前10个高频词
    vector<pair<string, int>> topWords(wordCount.begin(), wordCount.end());
    sort(topWords.begin(), topWords.end(), compare);
    cout << "\n前10个高频词：" << endl;
    for (int i = 0; i < min(10, static_cast<int>(topWords.size())); ++i) {
        cout << topWords[i].first << ": " << topWords[i].second << endl;
    }

    return 0;
}